from flask import Blueprint,jsonify, request
from main.BSL.friendBSL import *
from main.BSL import userBSL, noticeBSL
from main.utils import InterfaceHelper,RequestHelper
friend = Blueprint('friend',__name__)


@friend.route('/friend/add', methods=["POST"])
def add_friend():
    res = {}
    dic = RequestHelper.formToDict(request)
    try:
        friend_id = userBSL.query_username(dic['username'])
        if friend_id:
            friend_id = friend_id.id
            friend = Friend(user_id=dic['user_id'], friend_id=friend_id)
            insert(friend)
            res['status'] = 1
        else:
            res['status'] = 0
    except:
        res['status'] = 0
    return jsonify(res)


@friend.route('/friend/<int:user_id>')
def query_friend(user_id):
    res = {}
    data = []
    try:
        for i in query_friends(user_id):
            item = {}
            item['friend_id'] = i[0].friend_id
            item['username'] = i[1].username
            title = noticeBSL.query_user_id(i[0].friend_id)
            if title:
                title = title.title
            item['title'] = title
            data.append(item)
        res['data'] = data
        if data:
            res['status'] = 1
        else:
            res['status'] = 0
    except Exception as e:
        print(e)
    return jsonify(res)